<?php
/**
 * Модель category
 * 
 * Класс модели
 * @author Anton Zavidov
 * @package myLiveShop
 */

/**
 * Модель category
 *
 */
class ModelCategory extends Model {
	
	const TABLE				= 'category';
	const F_CATEGORY_ID  	= 'category_id';
	const F_PARENT_ID  	= 'parent_id';
	const F_SHOP_ID  	= 'shop_id';
	const F_MODEL  	= 'model';
	const F_PUBLISH  	= 'publish';
	const F_TITLE  	= 'title';
	const F_DESCRIPTION  	= 'description';
	const F_LANG_ID  	= 'lang_id';
	const F_COUNT_ELEMENTS  	= 'count_elements';
			
	public function __construct($className=null){
		parent::__construct(__CLASS__);
		$this->name='category';
		$this->id_field=array(self::F_CATEGORY_ID);
		$this->fields=array(
		self::TABLE.DOT.self::F_CATEGORY_ID=> new Field($this,self::F_CATEGORY_ID,self::TABLE,array(
				'auto'=>true,
				'important'=>true,
				'lenght'=>11)),
		self::TABLE.DOT.self::F_PARENT_ID=> new Field($this,self::F_PARENT_ID,self::TABLE,array(
				'important'=>true,
				'lenght'=>11,
				'join_table'=>'category')),
		self::TABLE.DOT.self::F_SHOP_ID=> new Field($this,self::F_SHOP_ID,self::TABLE,array(
				'lenght'=>11,
				'join_table'=>'shop')),
		self::TABLE.DOT.self::F_MODEL=> new Field($this,self::F_MODEL,self::TABLE,array(
				'important'=>true,
				'lenght'=>20,
				'type'=>Field::TYPE_STRING)),
		self::TABLE.DOT.self::F_PUBLISH=> new Field($this,self::F_PUBLISH,self::TABLE,array(
				'important'=>true,
				'lenght'=>1,
				'type'=>Field::TYPE_STRING,
				'validate_type'=>Validator::VALIDATE_HASH)),
		self::TABLE.DOT.self::F_TITLE=> new Field($this,self::F_TITLE,self::TABLE,array(
				'important'=>true,
				'lenght'=>255,
				'type'=>Field::TYPE_STRING)),
		self::TABLE.DOT.self::F_DESCRIPTION=> new Field($this,self::F_DESCRIPTION,self::TABLE,array(
				'important'=>true,
				'type'=>Field::TYPE_TEXT)),
		self::TABLE.DOT.self::F_LANG_ID=> new Field($this,self::F_LANG_ID,self::TABLE,array(
				'auto'=>true,
				'lenght'=>2,
				'join_table'=>'lang')),
		self::TABLE.DOT.self::F_COUNT_ELEMENTS=> new Field($this,self::F_COUNT_ELEMENTS,self::TABLE,array(
				'lenght'=>5))		);
	}
	//переопределяем save для того чтоб проверить на замыкание
	public function save($data,$id=false){
	    if(is_numeric($id) && isset($data[self::F_PARENT_ID]) && ($id == $data[self::F_PARENT_ID] || !$this->checkParent($data[self::F_PARENT_ID],$id))){
	       return array(self::TABLE.DOT.self::F_PARENT_ID=>'Замыкание');
	    }
	    return parent::save($data,$id);
	}
	/**
	 * рекурсивная проверка замыкания дерева
	 *
	 * @param int $parent_id
	 * @param int $id
	 * @return boolean
	 */
	public function checkParent($parent_id, $id){
	    if(!$parent_id)return true;
	    if($parent_id==$id)return false;
	    $item=$this->loadOne($parent_id,array(self::F_REGION_ID,self::F_PARENT_ID));
	    return $this->checkParent($item[self::F_PARENT_ID],$id);
	}
}
